package com.lightsaber.trade.core.dao.account;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.hibernate.HibernateDao;

import com.lightsaber.trade.core.entity.account.Menu;

@Component
public class MenuDao extends HibernateDao<Menu, Integer> {

    public Menu findByLevelPosition(final Byte level1Pos, final Byte level2Pos,
            final Byte level3Pos, final Byte level4Pos) {
        Criteria criteria = getSession().createCriteria(Menu.class);

        if (level1Pos != null) {
            criteria.add(Restrictions.eq("level1Pos", level1Pos));
        } else {
            criteria.add(Restrictions.isNull("level1Pos"));
        }

        if (level2Pos != null) {
            criteria.add(Restrictions.eq("level2Pos", level2Pos));
        } else {
            criteria.add(Restrictions.isNull("level2Pos"));
        }

        if (level3Pos != null) {
            criteria.add(Restrictions.eq("level3Pos", level3Pos));
        } else {
            criteria.add(Restrictions.isNull("level3Pos"));
        }

        if (level4Pos != null) {
            criteria.add(Restrictions.eq("level4Pos", level4Pos));
        } else {
            criteria.add(Restrictions.isNull("level4Pos"));
        }

        return (Menu) criteria.uniqueResult();
    }

    public List<Menu> findByAppCodeAndFuncCode(final String appCode, final String funcCode) {
        return this.find("from Menu m where m.appCode=? and m.funcCode=?", appCode, funcCode);
    }

    @SuppressWarnings("unchecked")
    public List<Menu> findByFuncCode(final String roleCode, final String userCode) {
        String hql = "select m from Menu m where exists ( "
                + "select 1 from UserRole ur, RoleAuthority ra where "
                + "ur.role=ra.role and ur.user.loginId=:userName and ur.role.name=:roleName "
                + "and m.funcCode=ra.authority.name)";

        Map<String, Object> values = new HashMap<String, Object>();
        values.put("userName", userCode);
        values.put("roleName", roleCode);

        Query q = this.createQuery(hql, values);
        return q.list();
    }

}
